package com.hqhsc.module.manage.channel.controller;

import com.hqhsc.module.common.service.CommonService;
import com.hqhsc.module.common.service.FileService;
import com.hqhsc.module.common.service.QrCodeService;
import com.hqhsc.module.init.service.InitService;
import com.hqhsc.module.login.domain.User;
import com.hqhsc.module.manage.activityuser.domain.ActivityUser;
import com.hqhsc.module.manage.channel.domain.Channel;
import com.hqhsc.module.manage.channel.service.ChannelManageService;
import com.hqhsc.utils.DateTimeUtil;
import com.hqhsc.utils.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

@Controller
@RequestMapping("/manage/channel")
public class ChannelManageController {
	final Logger logger = LoggerFactory.getLogger(ChannelManageController.class);

	@Autowired
	private CommonService commonService;
    @Autowired
    private ChannelManageService channelManageService;
    @Autowired
    private InitService initService;
    @Autowired
    private FileService fileService;
    @Autowired
    private QrCodeService qrCodeService;
	@Autowired
	private Properties appProps;

    /**
     * 渠道管理-渠道列表页
     * @param model
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/index" , method = {RequestMethod.GET , RequestMethod.POST})
    public String index(Model model , HttpServletRequest request , HttpServletResponse response) {
        User user = (User)request.getSession().getAttribute("user");

        String pageindexStr = request.getParameter("page_index");//第几页
        int page_index = Integer.parseInt(StringUtils.isBlank(pageindexStr) || "0".equals(pageindexStr) ? "1" : pageindexStr);
        int size = Integer.valueOf(appProps.get("manage.channel.index.size").toString());//每页显示条数
        int start = (page_index - 1) * size;

        String channel_name = request.getParameter("channel_name");

        String method = request.getMethod();
        if("GET".equals(method.toUpperCase()) && StringUtils.isNotEmpty(channel_name)) {//get请求，进行编码格式转换
            channel_name = this.commonService.characterFormat(channel_name , "ISO8859-1" , "UTF-8");
        }

        String channel_type = request.getParameter("channel_type");
        int channel_type_int = -1;
        if(StringUtils.isNotEmpty(channel_type)) {
            channel_type_int = Integer.valueOf(channel_type);
        }
        String orderby = request.getParameter("orderby");

        Map<String , Object> map = this.channelManageService.getChannelList(user.getRole_list().get(0).getOrg_id(), channel_name, channel_type_int , orderby , start, size);
        long total = (Long)map.get("total");
        List<Channel> channel_list = (List<Channel>)map.get("channel_list");

        Channel first_channel = new Channel();
        if(channel_list.size() > 0) {
            first_channel = channel_list.get(0);
        }

        long temp = (total - 1) <= 0 ? 0 : (total - 1);
        int pages = Integer.parseInt(Long.toString(temp / size)) + 1;
        int prepages = (page_index - 1) <= 0 ? 1 : (page_index - 1);
        int nextpages = (page_index + 1) >= pages ? pages : (page_index + 1);

        model.addAttribute("current_page" , page_index);
        model.addAttribute("pages" , pages);
        model.addAttribute("prepage" , prepages);
        model.addAttribute("nextpage" , nextpages);
        model.addAttribute("page_url" , request.getRequestURI());

        String condition = "";
        if(StringUtils.isNotEmpty(channel_name)) {
            condition = condition + "&channel_name="+channel_name;
        }
        if(StringUtils.isNotEmpty(channel_type)) {
            condition = condition + "&channel_type="+channel_type;
        }
        if(StringUtils.isNotEmpty(orderby)) {
            condition = condition + "&orderby="+orderby;
        }


        model.addAttribute("condition" , condition);
        model.addAttribute("channel_name" , channel_name);
        model.addAttribute("channel_type" , channel_type);
        model.addAttribute("orderby" , orderby);
        model.addAttribute("channel_list" , channel_list);
        model.addAttribute("first_channel" , first_channel);
        return "/module/manage/channel/index";
    }


    @RequestMapping(value = "/add" , method = RequestMethod.GET)
    public String addChannel(Model model , HttpServletRequest request , HttpServletResponse response) {
        User user = (User)request.getSession().getAttribute("user");

        return "/module/manage/channel/add";
    }


    @RequestMapping(value = "/doadd" , method = RequestMethod.POST)
    @ResponseBody
    public int channelDoAdd(Model model , HttpServletRequest request , HttpServletResponse response) {
        User user = (User)request.getSession().getAttribute("user");

        String channel_name = request.getParameter("channel_name");
        String channel_type = request.getParameter("channel_type");
        String website_url = request.getParameter("website_url");
        String spread_position = request.getParameter("spread_position");
        String spread_cycle = request.getParameter("spread_cycle");
        String spread_content = request.getParameter("spread_content");
        String spread_cost = request.getParameter("spread_cost");


        return this.channelManageService.channelDoAdd(1 , channel_name,Integer.valueOf(channel_type),website_url,spread_position,spread_cycle,spread_content,Integer.valueOf(spread_cost) , user.getUser_id());
    }

    @RequestMapping(value = "/edit" , method = RequestMethod.GET)
    public String editChannel(Model model , HttpServletRequest request , HttpServletResponse response) {
        User user = (User)request.getSession().getAttribute("user");

        String edited_channel_id = request.getParameter("edited_channel_id");
        Channel channel_info = this.channelManageService.getChannelById(Long.valueOf(edited_channel_id));
        model.addAttribute("channel_info" , channel_info);
         

        return "/module/manage/channel/edit";
    }

    @RequestMapping(value = "/doedit" , method = RequestMethod.POST)
    @ResponseBody
    public int channelDoEdit(Model model , HttpServletRequest request , HttpServletResponse response) {
        User user = (User)request.getSession().getAttribute("user");

        String channel_name = request.getParameter("channel_name");
        String channel_type = request.getParameter("channel_type");
        String spread_position = request.getParameter("spread_position");
        String spread_cycle = request.getParameter("spread_cycle");
        String spread_content = request.getParameter("spread_content");
        String spread_cost = request.getParameter("spread_cost");
        String channel_id = request.getParameter("channel_id");
        return this.channelManageService.channelDoEdit(Long.valueOf(channel_id) , user.getRole_list().get(0).getOrg_id(), channel_name,Integer.valueOf(channel_type),spread_position,spread_cycle,spread_content,Integer.valueOf(spread_cost) , user.getUser_id());
    }


    @RequestMapping(value = "/detail" , method = RequestMethod.GET)
    public String channelDetail(Model model , HttpServletRequest request , HttpServletResponse response) {
        User user = (User)request.getSession().getAttribute("user");

        String channel_id = request.getParameter("channel_id");
        Channel channel_info = this.channelManageService.getChannelById(Long.valueOf(channel_id));
        model.addAttribute("channel_info" , channel_info);


        return "/module/manage/channel/detail";
    }


    @RequestMapping(value = "/export" , method = RequestMethod.GET)
    public void exportChannel(Model model , HttpServletRequest request , HttpServletResponse response) throws IOException {
        User user = (User)request.getSession().getAttribute("user");

        String channel_ids = request.getParameter("channel_ids");
        List<Channel> channel_list = this.channelManageService.getChannelListByIds(channel_ids);

        String base_path = request.getSession().getServletContext().getRealPath("/");
        String file_path = appProps.getProperty("channel.download.realpath");
        String file_name = "渠道合集";
        if(channel_list.size() <= 1) {
            file_name = channel_list.get(0).getName();
        }

        String path = base_path + file_path + file_name + "-" + DateUtil.getDate(new Date() , "yyyy-MM-dd") +".xls";
        this.fileService.writeChannelExcel(channel_list , path);

        this.fileService.exportFile(response , new File(path) , false);
    }


    @RequestMapping(value = "/qrcode" , method = RequestMethod.GET)
    public void channelQrCode(Model model , HttpServletRequest request , HttpServletResponse response) throws IOException {
        User user = (User)request.getSession().getAttribute("user");

        String channel_id = request.getParameter("channel_id");
        Channel channel = this.channelManageService.getChannelById(Long.valueOf(channel_id));

        String base_path = request.getSession().getServletContext().getRealPath("/");
        String file_path = appProps.getProperty("channel.qrcode.download.realpath");
        String file_name = channel.getName();

        String path = base_path + file_path + file_name + "-qr-" + DateUtil.getDate(new Date() , "yyyy-MM-dd") +".png";
        this.qrCodeService.encoderQRCode(channel.getWebsite_url() , path , "png" , 20);

        this.fileService.exportFile(response , new File(path) , false);
    }



}